<template>
  <el-popover
      placement="bottom"
      :width="300"
      :visible="visible"
      @show="handleShow"
      @hide="handleHide"
      ref="popover"
  >
    <template #reference>
      <el-input
          ref="input"
          v-model="date"
          @change="handleChange"
          placeholder="请选择日期"
          :prefix-icon="Calendar"
          clearable
          @focus="visible = true"
          @blur="visible = false"
          v-on="$attrs"
      />
    </template>
    <div>
      <el-calendar :value="date" ref="calendar" @input="chooseDate">
        <template #header="{ date }">
          <span>{{ date }}</span>
        </template>
      </el-calendar>
    </div>
  </el-popover>
</template>

<script setup lang="ts">
  import {Calendar} from "@element-plus/icons-vue";
  import { ref,onMounted,watch } from 'vue'
  import type { CalendarDateType, CalendarInstance } from 'element-plus'
  import dayjs from "dayjs";

  const date = ref('')
  const prop = defineProps({
    modelValue: {
      type: String,
      default: () => ''
    }
  })

  const emit = defineEmits(['update:modelValue'])
  const visible = ref(false)
  watch(() => date.value, (newValue) => {
    emit('update:modelValue', newValue)
  })
  const handleChange = (val) => {
    if (!calendar.value) return
    calendar.value?.$emit('input', new Date(val))
  }
  const calendar = ref<CalendarInstance>()
  const popover = ref()
  const input = ref()
  const selectDate = (val: CalendarDateType) => {
    if (!calendar.value) return
    calendar.value.selectDate(val)
  }
  const handleWheel = (event) => {
    // 检查滚轮滚动的方向
    if (event.deltaY > 0) {
      selectDate('next-month')
    } else {
      selectDate('prev-month')
    }
  }
  const handleShow = () => {
    document.addEventListener('wheel', handleWheel);
    window.addEventListener('scroll', function(event) {
      event.preventDefault();
    }, { passive: false });
  }
  const handleHide = () => {
    document.removeEventListener('wheel', handleWheel);
    window.removeEventListener('scroll', function(event) {
      event.preventDefault();
    });
  }
  const chooseDate = (val) =>{
    date.value = dayjs(val).format('YYYY-MM-DD')
  }
  onMounted(() => {
    date.value = prop.modelValue
  })
</script>

<style lang="scss" scoped>
 :deep(.el-calendar-day) {
   height: 40px;
 }
</style>
